package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.ruoyi.system.domain.PwsStatus;
import com.ruoyi.system.domain.PwsTable;
import com.ruoyi.system.https.bo.ZMES_GET_PWOH_REPONSE;
import com.ruoyi.system.https.vo.ZMES_GET_PWOH_REQUEST;
import com.ruoyi.system.mapper.PwsTableMapper;
import com.ruoyi.system.service.IOrderqaInfoService;
import com.ruoyi.system.service.PwsStatusService;
import com.ruoyi.system.service.PwsTableService;
import com.ruoyi.system.service.SapDataService;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

/**
 * <p>
 * pws 服务实现类
 * </p>
 *
 * @author tianfu-li
 * @since 2025-44-27
 */
@Service
public class PwsTableServiceImpl extends ServiceImpl<PwsTableMapper, PwsTable> implements PwsTableService {
    @Autowired
    ExternalApiService externalApiService;
    @Autowired
    SapDataService sapDataService;
    @Autowired
    IOrderqaInfoService orderqaInfoService;
    @Autowired
    PwsStatusService pwsStatusService;
    @Value("${sap.ZMES_GET_PWOH.url}")
    private String ZMES_GET_PWOH_Url;
    @Value("${sap.ZMES_GET_PWOH.SOAPAction}")
    private String ZMES_GET_PWOH_SOAPAction;
    @Value("${sap.auth.user}")
    private String user;
    @Value("${sap.auth.password}")
    private String password;

    @Override
    public List<PwsTable> getPwsTableByOrderNoOrOrderStartDate(String orderNo, LocalDateTime orderStartDate) {
        LambdaQueryWrapper<PwsTable> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(orderNo)){
            queryWrapper.eq(PwsTable::getOrderNo,orderNo);
        }
        if(orderStartDate!=null){
            queryWrapper.likeLeft(PwsTable::getOrderStartDate,orderStartDate);

        }
        return this.list(queryWrapper);
    }


    @Override
    public boolean getPwoBySap(Date date, String userId) throws JsonProcessingException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //通过ZWS PPGET PWOH 接口从 sap 获取数据
        ZMES_GET_PWOH_REQUEST.Item item = new ZMES_GET_PWOH_REQUEST.Item();
        ZMES_GET_PWOH_REQUEST.Pwoh pwoh = new ZMES_GET_PWOH_REQUEST.Pwoh();
        pwoh.setItem(item);
        ZMES_GET_PWOH_REQUEST.ZmesGetPwoh zmesGetPwoh = new ZMES_GET_PWOH_REQUEST.ZmesGetPwoh();
        zmesGetPwoh.setOrderStatus("REL");
        zmesGetPwoh.setPlant("SG");
        zmesGetPwoh.setPwoh(pwoh);
        zmesGetPwoh.setStartDate(sdf.format(date));
        ZMES_GET_PWOH_REQUEST.SoapBody body = new ZMES_GET_PWOH_REQUEST.SoapBody();
        body.setZmesGetPwoh(zmesGetPwoh);
        ZMES_GET_PWOH_REQUEST request = new ZMES_GET_PWOH_REQUEST();
        request.setBody(body);
        //转成xml
        XmlMapper xmlMapper=new XmlMapper();
        ObjectWriter objectWriter=xmlMapper.writerWithDefaultPrettyPrinter();
        String xml = objectWriter.writeValueAsString(request);
        //设置请求头的额外参数
        //添加SOAPAction
        Map<String,String> headerParamsMap=new HashMap<>();
        headerParamsMap.put("Content-Type", "text/xml;charset=UTF-8");
        headerParamsMap.put("Accept", "text/xml");
        headerParamsMap.put("User_Agent","Apache-HttpClient/4.5.5 (Java/17.0.12)");
        headerParamsMap.put("Accept_Encoding","gzip,deflate");
        headerParamsMap.put("Content_Length","1074");
        headerParamsMap.put("Host","s4suitedevapp.nipponpaint.com.sg:8200");
        headerParamsMap.put("Connection","Keep-Alive");
        if(StringUtils.isNotBlank(ZMES_GET_PWOH_SOAPAction)) {
            headerParamsMap.put("SOAPAction", ZMES_GET_PWOH_SOAPAction);
        }
        // 添加基本认证信息
        if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
            String auth = user + ":" + password; // 替换为你的用户名和密码
            byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
            String authHeader = "Basic " + new String(encodedAuth);
            headerParamsMap.put("Authorization", authHeader);
        }
        //调用sap接口
        ZMES_GET_PWOH_REPONSE zmes_get_pwoh_reponse=externalApiService.callExternalApi(ZMES_GET_PWOH_Url, HttpMethod.POST, headerParamsMap,null,xml,ZMES_GET_PWOH_REPONSE.class);
        //String  zmes_get_pwoh_reponse=externalApiService.callExternalApi(ZMES_GET_PWOH_Url, HttpMethod.GET, MediaType.APPLICATION_XML,MediaType.TEXT_XML,null,xml,String.class);


        return dealResponse(zmes_get_pwoh_reponse,userId);
    }

    @Override
    public List<PwsTable> selectByPrimaryKeyFromOrderNo(String orderNo, LocalDate orderStartDate, String orderType) {
        LambdaQueryWrapper<PwsTable> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(orderNo)){
            queryWrapper.eq(PwsTable::getOrderNo,orderNo);
        }
        if(StringUtils.isNotBlank(orderType)){
            queryWrapper.eq(PwsTable::getOrderType,orderType);
        }
        if(orderStartDate!=null){
            queryWrapper.like(PwsTable::getOrderStartDate,orderStartDate);

        }
        return this.list(queryWrapper);
    }

    public PwsTable getPwsTableByOrderNo(String orderNo){
        LambdaQueryWrapper<PwsTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PwsTable::getOrderNo,orderNo);
        return this.getOne(queryWrapper);
    }
    @Transactional(rollbackFor = Exception.class)
    public   boolean dealResponse(ZMES_GET_PWOH_REPONSE zmes_get_pwoh_reponse,String userId) throws JsonProcessingException {
        if(zmes_get_pwoh_reponse==null){
            return false;
        }else {
            //接口返回结果映射未pwsTable对象
            List<PwsTable> pwsTableList = ZMES_GET_PWOH_REPONSE.bodyToPwsTable(zmes_get_pwoh_reponse);
            //TODO:pws_status is_ready>0
            //判断存不存在
            for (PwsTable pwsTable : pwsTableList) {
                PwsTable LocalpwsTable = getPwsTableByOrderNo(pwsTable.getOrderNo());
                //查询pws_status
                PwsStatus pwsStatus = pwsStatusService.getPwsStatusByOrderNo(pwsTable.getOrderNo());
                if(pwsStatus==null){
                    PwsStatus pwsStatus1 = new PwsStatus(pwsTable.getOrderNo(),LocalDateTime.now());
                    pwsStatusService.save(pwsStatus1);
                }
                if(pwsStatus==null||pwsStatus.getIsReady()==0) {
                    if (LocalpwsTable == null) {
                        this.save(pwsTable);
                    } else {
                        pwsTable.setId(LocalpwsTable.getId());
                        this.updateById(pwsTable);
                    }
                }
                //将从接口获取到的单号循环调用 ZWS_PP_GET_PWOI 接口从 sap 获取订单数据。
                sapDataService.updateSapDataBySap(pwsTable.getOrderNo(), userId);
                //从接口获取到的单号循环调用 ZWS_PP_GET_PWOQA 接口从 sap 获取订单qa数据。
                orderqaInfoService.updateOrderqaInfoBySap(pwsTable.getOrderNo(), userId);
            }
            return true;
        }
    }
}
